package org.firebug.spring.boot.mq;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitmqConsumer {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * spring.rabbitmq.listener.simple.acknowledge-mode = none
     * spring.rabbitmq.listener.simple.acknowledge-mode = auto
     */
//    @RabbitListener(queues = {"queue.000"})
//    public void handle(Message message, Channel channel) {
//        logger.info("thread: {}, consume: {}", Thread.currentThread().getName(), new String(message.getBody()));
//    }

    /**
     * spring.rabbitmq.listener.simple.acknowledge-mode=manual
     */
    @RabbitListener(queues = {"queue.000"})
    public void handle(Message message, Channel channel) throws IOException {
        try {
            logger.info("thread: {}, consume: {}, deliveryTag: {}", Thread.currentThread().getName(), new String(message.getBody()), message.getMessageProperties().getDeliveryTag());
            if (true) throw new RuntimeException("fuck");
            //TODO
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);// 确认单条消息
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); // 确认批量消息
        } catch (Exception e) {
            logger.warn("thread: {}, reject: {}", Thread.currentThread().getName(), e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);//拒绝单条消息
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);//拒绝批量消息
        }
    }
}

